﻿/*
 * Greenshot - a free and open source screenshot tool
 * Copyright (C) 2013 Robin Krom
 * 
 * For more information see: http://getgreenshot.org/
 * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 1 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System.Collections.Generic;
using System.Security.Principal;
using System.ServiceModel;
using System.Windows;
using Greenshot.IniFile;
using Greenshot2.ContextMenu;
using Greenshot2.Contract;
using Greenshot2Core.Core;
using Greenshot2Core.Interfaces;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace Greenshot2 {
	/// <summary>
	/// This is the application logic belonging to the App.xaml
	/// </summary>
	public partial class App : Application {
		private static NLog.Logger LOG = NLog.LogManager.GetCurrentClassLogger();
		private ContractImpl server = null;
		private CoreConfiguration coreConfiguration;
		// We use the TaskbarIcon from here: http://www.codeproject.com/Articles/36468/WPF-NotifyIcon
		private TrayIcon taskbarIcon;

		/// <summary>
		/// Here the plugins are automatically load
		/// </summary>
		[ImportMany]
		public IEnumerable<IGreenshotPlugin> Plugins {
			get;
			set;
		}

		/// <summary>
		/// Use the MEF (Managed Extensibility Framework) to load the plugins from the path
		/// </summary>
		/// <param name="path"></param>
		private void MEFPluginLoader(string path)  {
			DirectoryCatalog directoryCatalog = new DirectoryCatalog(path);

			//An aggregate catalog that combines multiple catalogs
			var catalog = new AggregateCatalog(directoryCatalog);

			// Create the CompositionContainer with all parts in the catalog (links Exports and Imports)
			CompositionContainer container = new CompositionContainer(catalog);

			//Fill the imports of this object
			container.ComposeParts(this);
		}

		/// <summary>
		/// Start Greenshot, this is the first code that is initiated.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="startupEventArgs"></param>
		private void GreenshotStart(object sender, StartupEventArgs startupEventArgs) {
			// Get the session token, this should be unique for every session in Windows
			string sessionToken = WindowsIdentity.GetCurrent().User.ToString();
			try {
				// Create the server, so it can handle calls from clients
				server = ContractImpl.Instance(sessionToken);
				LOG.Info("Greenshot server started!");

				// Initialize the IniConfig
				IniConfig.Init();
				coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>();

				// Start the plugin loader, and initialize every plugin
				MEFPluginLoader(".");
				foreach (IGreenshotPlugin plugin in Plugins) {
					plugin.Initialize();
				}

				// start GUI
				createGUI();

			} catch (AddressAlreadyInUseException) {
				LOG.Info("Greenshot server was already running.");
			}
			if (startupEventArgs.Args.Length > 0) {
				// Now behave as client (passing commandline arguments etc)
				// If arguments are available, pass them through to the server (which might also be this instance)
				List<string> filesToOpen = new List<string>();
				for (int argumentNr = 0; argumentNr < startupEventArgs.Args.Length; argumentNr++) {
					string argument = startupEventArgs.Args[argumentNr];
					filesToOpen.Add(argument);
				}
				if (filesToOpen.Count > 0) {
					using (ChannelFactory<IGreenshot2Contract> pipeFactory = new ChannelFactory<IGreenshot2Contract>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/Greenshot_" + sessionToken))) {
						IGreenshot2Contract greenshotServer = pipeFactory.CreateChannel();
						foreach (string filename in filesToOpen) {
							greenshotServer.OpenFile(filename);
						}
					}
				}
			}

			// "exit"
			if (server == null) {
				LOG.Info("exiting this instance");
				// When no server we shutdown
				Application.Current.Shutdown();
			} else {
				// When a server we just return and let the GUI do the rest of the work
				return;
			}
		}

		/// <summary>
		/// Create the Greenshot GUI elements, in our case the TrayIcon
		/// </summary>
		private void createGUI() {
			taskbarIcon = new TrayIcon();
		}
	}
}
